using System;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace Wra4Skype.Library
{
    public class WraProvider : IRemoteAssistanceProvider
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "The use of exposed method is protected here. There can be no improper use by callers.")]
        public string CreateInvitation(string password)
        {
            var tempFile = Path.GetTempFileName();

            // create an invitation file into a temporary file
            var process = new Process();
            process.StartInfo.FileName = "msra.exe";
            process.StartInfo.Arguments = "/saveasfile \"{0}\" {1}".Format2(tempFile, password);
            process.Start();

            // msra adds a standard extension to the file
            tempFile += ".msrcincident";

            // wait for some time for file to be created. check every now and then if it is created.
            var watch = new Stopwatch();
            watch.Start();
            while (!File.Exists(tempFile) && watch.ElapsedMilliseconds < 15000)
            {
                Thread.Sleep(300);
            }

            if (!File.Exists(tempFile))
            {
                throw new InvalidOperationException("Failed to create invitation!");
            }

            // read invitation content and delete the temp file
            var invitationContent = File.ReadAllText(tempFile);
            File.Delete(tempFile);
            return invitationContent;
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "The use of exposed method is protected here. There can be no improper use by callers.")]
        public void UseInvitation(InvitationMessage invitationMessage)
        {
            // write invitation xml into a temporary file
            var tempFile = Path.GetTempFileName() + ".msrcincident";
            File.WriteAllText(tempFile, invitationMessage.InvitationXml);

            // start remote assistance
            var process = new Process();
            process.StartInfo.FileName = "msra.exe";
            process.StartInfo.Arguments = "/openfile \"{0}\"".Format2(tempFile);
            process.Start();
        }
    }
}